// pages/student/practice/practice.js
Page({
  data: {
    courseId: null,
    courseName: '',
    assignmentTitle: '第一章课后练习',
    totalScore: 100,
    timeLimit: 3600, // 秒
    remainingTime: 3600,
    currentIndex: 0,
    questions: [
      {
        id: 1,
        type: 'single_choice',
        question: '微信小程序的配置文件是？',
        options: ['app.js', 'app.json', 'app.wxss', 'app.wxml'],
        correctAnswer: '1',
        userAnswer: null,
        points: 10
      },
      {
        id: 2,
        type: 'multiple_choice',
        question: '以下哪些是小程序的生命周期函数？（多选）',
        options: ['onLoad', 'onShow', 'onReady', 'onCreate'],
        correctAnswer: ['0', '1', '2'],
        userAnswer: [],
        points: 15
      },
      {
        id: 3,
        type: 'fill_blank',
        question: '小程序的数据绑定使用______语法。',
        correctAnswer: '{{}}',
        userAnswer: '',
        points: 10
      },
      {
        id: 4,
        type: 'single_choice',
        question: '小程序页面的样式文件扩展名是？',
        options: ['.css', '.wxss', '.scss', '.less'],
        correctAnswer: '1',
        userAnswer: null,
        points: 10
      },
      {
        id: 5,
        type: 'multiple_choice',
        question: '小程序支持的数据请求方式有？（多选）',
        options: ['wx.request', 'wx.downloadFile', 'wx.uploadFile', 'wx.fetch'],
        correctAnswer: ['0', '1', '2'],
        userAnswer: [],
        points: 15
      }
    ],
    showResult: false,
    timer: null
  },
  onLoad(options) {
    const courseId = options.courseId
    const courseName = options.courseName || '课程'
    this.setData({ 
      courseId,
      courseName 
    })
    this.startTimer()
  },
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
  },
  startTimer() {
    const timer = setInterval(() => {
      let { remainingTime } = this.data
      remainingTime--
      if (remainingTime <= 0) {
        clearInterval(timer)
        this.submitPractice()
        return
      }
      this.setData({ remainingTime })
    }, 1000)
    this.setData({ timer })
  },
  formatTime(seconds) {
    const h = Math.floor(seconds / 3600)
    const m = Math.floor((seconds % 3600) / 60)
    const s = seconds % 60
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  },
  prevQuestion() {
    const { currentIndex } = this.data
    if (currentIndex > 0) {
      this.setData({ currentIndex: currentIndex - 1 })
    }
  },
  nextQuestion() {
    const { currentIndex, questions } = this.data
    if (currentIndex < questions.length - 1) {
      this.setData({ currentIndex: currentIndex + 1 })
    }
  },
  selectSingleChoice(e) {
    const { index } = e.currentTarget.dataset
    const { currentIndex, questions } = this.data
    questions[currentIndex].userAnswer = index.toString()
    this.setData({ questions })
  },
  selectMultipleChoice(e) {
    const { index } = e.currentTarget.dataset
    const { currentIndex, questions } = this.data
    const question = questions[currentIndex]
    const indexStr = index.toString()
    
    if (!question.userAnswer) {
      question.userAnswer = []
    }
    
    const answerIndex = question.userAnswer.indexOf(indexStr)
    if (answerIndex > -1) {
      question.userAnswer.splice(answerIndex, 1)
    } else {
      question.userAnswer.push(indexStr)
    }
    
    this.setData({ questions })
  },
  inputFillBlank(e) {
    const { value } = e.detail
    const { currentIndex, questions } = this.data
    questions[currentIndex].userAnswer = value
    this.setData({ questions })
  },
  submitPractice() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    
    wx.showModal({
      title: '确认提交',
      content: '提交后将无法修改答案，确认提交吗？',
      success: (res) => {
        if (res.confirm) {
          this.calculateScore()
        }
      }
    })
  },
  calculateScore() {
    const { questions, totalScore, timeLimit, remainingTime } = this.data
    let correctCount = 0
    let totalPoints = 0
    let earnedPoints = 0
    
    questions.forEach(q => {
      totalPoints += q.points
      let isCorrect = false
      
      if (q.type === 'single_choice') {
        isCorrect = q.userAnswer === q.correctAnswer
      } else if (q.type === 'multiple_choice') {
        if (q.userAnswer && q.correctAnswer) {
          const userSet = new Set(q.userAnswer.sort())
          const correctSet = new Set(q.correctAnswer.sort())
          isCorrect = userSet.size === correctSet.size && 
                     [...userSet].every(val => correctSet.has(val))
        }
      } else if (q.type === 'fill_blank') {
        isCorrect = q.userAnswer.trim() === q.correctAnswer.trim()
      }
      
      if (isCorrect) {
        correctCount++
        earnedPoints += q.points
      }
    })
    
    const score = Math.round((earnedPoints / totalPoints) * totalScore)
    const timeTaken = timeLimit - remainingTime
    
    wx.redirectTo({
      url: `/pages/student/practice-result/practice-result?score=${score}&total=${totalScore}&correct=${correctCount}&totalQuestions=${questions.length}&timeTaken=${timeTaken}`
    })
  },
  exitPractice() {
    wx.showModal({
      title: '确认退出',
      content: '退出后将不保存答题记录，确认退出吗？',
      success: (res) => {
        if (res.confirm) {
          if (this.data.timer) {
            clearInterval(this.data.timer)
          }
          wx.navigateBack()
        }
      }
    })
  }
})
